package com.vhall.component.plugin.common.support;

import com.alibaba.fastjson.JSON;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * @author yongzheng.xu
 * @date 2021/8/12 17:38
 */
@Slf4j
@Service("ps")
public class PermissionSupport {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 所有权限标识
     */
    private static final String ALL_PERMISSION = "*:*:*";

    /**
     * 管理员角色权限标识
     */
    private static final String SUPER_ADMIN = "admin";

    private static final String ROLE_DELIMIT = ",";

    private static final String PERMISSION_DELIMIT = ",";

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission, AdmToken token) {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        AdmToken admin = appendPermi(token);
        if (null == admin || CollectionUtils.isEmpty(admin.getPermissions())) {
            return false;
        }
        return hasPermissions(admin.getPermissions(), permission);
    }

    /**
     * 验证用户是否不具备某权限，与 hasPermi逻辑相反
     *
     * @param permission 权限字符串
     * @return 用户是否不具备某权限
     */
    public boolean lacksPermi(String permission, AdmToken token) {
        return hasPermi(permission, token) != true;
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表
     * @return 用户是否具有以下任意一个权限
     */
    public boolean hasAnyPermi(String permissions, AdmToken token) {
        if (StringUtils.isEmpty(permissions)) {
            return false;
        }
        AdmToken admin = appendPermi(token);
        if (null == admin || CollectionUtils.isEmpty(admin.getPermissions())) {
            return false;
        }
        Set<String> authorities = admin.getPermissions();
        for (String permission : permissions.split(PERMISSION_DELIMIT)) {
            if (permission != null && hasPermissions(authorities, permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否包含权限
     *
     * @param permissions 权限列表
     * @param permission  权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(Set<String> permissions, String permission) {
        return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public AdmToken appendPermi(AdmToken tk) {
        // 获取请求携带的令牌
        try {

            Integer roleId = tk.getRoleId();
            // 得到了权限
            String pri = redisTemplate.opsForValue().get(RedisKey.ROLE_PERMISSION + roleId);
            tk.setPermissions(JSON.parseObject(pri, Set.class));
        } catch (Throwable e) {
            log.error("查询权限失败:", e);
            throw new BusinessException(BizErrorCode.BIZ_NO_PERMISSION);
        }
        return tk;
    }

}
